import axios from 'axios'
import store from '@/store'
import { Toast } from 'vant';
import i18n from "@/i18n";
import { BASE_URL } from "@/config";
import router from '@/router/router'
import { getSessionStorage } from '@/utils/utis'
import { signatureGenerate } from "@/utils/signatureUtil"
import {decryptText, encryptText, objectToQueryString} from "@/utils/aes"
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
import {isMobile} from "@/utils/utis";
import {generateFingerprint} from "@/utils/generateFingerprint";
let deviceStr = `deviceType=H5&physicalId=${generateFingerprint()}`
let baseUrl = BASE_URL
if (getSessionStorage('tzlj')) {
  baseUrl = getSessionStorage('tzlj');
}

// 创建
const request = axios.create({
  baseURL: baseUrl,
  timeout: 10000, // 超时时间
  //   withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  //   transformRequest: [function(data) {
  //     return data
  //   }]
})
// 拦截请求
request.interceptors.request.use(config => {
  if (config.loading) {
    Toast.loading({ duration: 0, forbidClick: true })
  }

  var token = store.state.user.userInfo.token
  //加密传参
  let nowStr = "";
  if (config.method === 'post') {
    let strArr = [] //参数集合
    if (config.data instanceof Object) {
      strArr = strArr.concat(
          Object.entries(config.data)
              .map(([key, value]) => `${key}=${value}`)
      );
    }  
    if(token)
    {
      nowStr = strArr.length>0 ? strArr.join("&")+'&token='+token + '&' + deviceStr :'token='+token + '&' + deviceStr; //拿到传参的参数和值
    }else{
      nowStr = strArr.length>0 ? strArr.join("&") + '&' + deviceStr : deviceStr
    }
    // console.log('11111',`${nowStr} \n ${config.url}`)
    let str = ''
    //没有参数不加密
    if(nowStr){
      str = `cipherTextKey=${encodeURIComponent(encryptText(nowStr))}`
      config.data=nowStr
    }else {
      config.data=nowStr
    }

  }else{
    if (token) {
      if (!config.params) {
        config.params = {}
      }
      config.params.token = token;
    }
    nowStr = objectToQueryString(config.params);
    config.params = {
      cipherTextKey:encryptText(nowStr)
    }
  }
  //加密传参需再传xcry=true
  config.headers["xcry"] = true;
  //返回加密数据需再传ycry=true,在api配置加上isDecrypt,如果等于 1，则不需要传ycry 接口解密打开下面这个
  // if(config.isDecrypt !== 1){
  //   config.headers["ycry"] = true;
  // }
  // 获取请求头参数
  const { timestamp, signature, systemRandom } = signatureGenerate()
  if (timestamp) config.headers['tissuePaper'] = timestamp;
  if (signature) config.headers['sign'] = signature;
  if (systemRandom) config.headers["systemRandom"] = systemRandom
  return config
}, error => {
  Promise.reject(error)
})

/**
 * 烤猫, [7/27/2022 9:08 PM]
 * 0 成功
1 直接显示
105 直接提示“当前还需交易“ + 返回的金额值 + ”,才可提币"
401 是需要实名认证，问客户”未实名认证，是否认证？"
403 无登录信息，跳转登录页面
506 "帐户异常需要进行C3认证，请联系在线客服。"
 */

// 拦截响应
request.interceptors.response.use(res => { // 200开头的
  if (res.config.loading) {
    Toast.clear()
  }
  //在api配置加上isDecrypt,如果等于 1，则不需要解密 接口解密打开下面这个
  //let { code, data, msg } = res.config.isDecrypt !== 1 ? decryptText(res.data) : res.data
  let { code, data, msg } = res.data
  switch (code / 1) {
    case 0:
      return Promise.resolve(data)
    case 403:
    case 297:
    case 214:
    case 213:
      router.replace({
        path: '/login',
        query: {
          redirect: router.currentRoute.fullPath
        }
      });
      localStorage.removeItem("verifyData");
      store.commit('user/SET_OUT');
      return Promise.reject('reject').catch(error => {
        console.error('reject:', error);
      });
    break;
    default:
      if (msg != undefined) {
        Toast.fail({
          // icon: 'none',
          message: i18n.t(msg)
        });
      }
      //console.log('错误')
      return Promise.reject(res.config.isDecrypt !== 1 ? decryptText(res.data) : res.data)
      // return Promise.reject(res.data)
  }
}, error => {
  if (error.code == 'ERR_NETWORK') {
    Toast({ message: 'ERR_NETWORK', type: 'fail', duration: 1000 })
  } else if (error.code == 'ECONNABORTED') {
    //Toast({ message: 'Network Timeout', type: 'fail', duration: 2000 })
    return Promise.reject(error);
  } else if (error && error.response) {
    //console.log(error.response);
    switch (error.response.status) {
      case 201: error.message = i18n.t('timestamp is empty'); break
      case 202: error.message = i18n.t('request expired'); break
      case 205: error.message = i18n.t('signature is empty'); break
      case 206: error.message = i18n.t('signature failed'); break
      case 207: error.message = i18n.t('timestamp and random number are empty'); break
      case 208: error.message = i18n.t('the current request timestamp and random number are the same as last time, the request is rejected'); break
      case 211: error.message = i18n.t('wrong ip address'); break
      case 212: error.message = i18n.t('ip black list verification failed'); break
      case 213: error.message = i18n.t('token was not submitted'); break
      case 214: error.message = i18n.t('token has expired'); break
      case 277: error.message = i18n.t('access content contains sensitive words'); break
      case 400: error.message = i18n.t('请求错误'); break
      case 401: error.message = i18n.t('未授权，请登录'); break
      case 403: error.message = i18n.t('拒绝访问'); break
      case 297: error.message = i18n.t('拒绝访问'); break
      case 404: error.message = i18n.t(`请求地址不存在: ${error.response.config.url}`); break
      case 405: error.message = i18n.t('network anomalies, please try again later'); break
      case 408: error.message = i18n.t('请求超时'); break
      case 500: error.message = i18n.t('服务器内部错误'); break
      case 501: error.message = i18n.t('服务未实现'); break
      case 502: error.message = i18n.t('网关错误'); break
      case 503: error.message = i18n.t('服务不可用'); break
      case 504: error.message = i18n.t('网关超时'); break
      case 505: error.message = i18n.t('HTTP版本不受支持'); break
      case 506: error.message = i18n.t('account abnormality requires C3 authentication, please contact online customer service'); break
      default: error.message = i18n.t('未捕获到的状态码'); break
    }
  }
  // eslint-disable-next-line prefer-promise-reject-errors
  return Promise.reject(error);
}
)
export default request
